import 'package:flutter/material.dart';
import '../models/document.dart';

class DocumentList extends StatefulWidget {
  final List<Document> documents;
  final String? selectedDocId;
  final Function(String) onDocumentSelected;
  final bool isLoading;

  const DocumentList({
    super.key,
    required this.documents,
    this.selectedDocId,
    required this.onDocumentSelected,
    this.isLoading = false,
  });

  @override
  State<DocumentList> createState() => _DocumentListState();
}

class _DocumentListState extends State<DocumentList> {
  // 存储展开状态的集合（存储文档ID）
  final Set<String> _expandedIds = {};

  @override
  void initState() {
    super.initState();
    // 初始化时如果有选中项，展开其路径
    if (widget.selectedDocId != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _updateExpandedState();
      });
    }
  }

  @override
  void didUpdateWidget(DocumentList oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 当选中项改变时，更新展开状态
    if (widget.selectedDocId != oldWidget.selectedDocId && widget.selectedDocId != null) {
      _updateExpandedState();
    }

    // 当文档列表更新时，如果有选中项，确保其路径已展开
    if (widget.documents != oldWidget.documents && widget.selectedDocId != null) {
      _updateExpandedState();
    }
  }

  /// 更新展开状态：确保选中项的所有父节点都展开
  void _updateExpandedState() {
    if (widget.selectedDocId == null) return;

    final pathToSelected = _findPathToDocument(widget.documents, widget.selectedDocId!);

    setState(() {
      // 不清空现有展开状态，只添加选中项路径上的节点
      // 确保选中项的所有父节点都展开
      if (pathToSelected.length > 1) {
        // 添加所有父节点到展开列表（不包括最后一个节点本身）
        _expandedIds.addAll(pathToSelected.sublist(0, pathToSelected.length - 1));
      }
      // 如果选中的节点有子节点，也展开它
      final selectedDoc = _findDocumentById(widget.documents, widget.selectedDocId!);
      if (selectedDoc != null && selectedDoc.children.isNotEmpty) {
        _expandedIds.add(widget.selectedDocId!);
      }
    });
  }

  /// 根据ID查找文档
  Document? _findDocumentById(List<Document> documents, String targetId) {
    for (final doc in documents) {
      if (doc.id == targetId) {
        return doc;
      }
      if (doc.children.isNotEmpty) {
        final found = _findDocumentById(doc.children, targetId);
        if (found != null) return found;
      }
    }
    return null;
  }

  /// 递归查找文档路径
  List<String> _findPathToDocument(List<Document> documents, String targetId, [List<String> path = const []]) {
    for (final doc in documents) {
      final currentPath = [...path, doc.id];

      if (doc.id == targetId) {
        return currentPath;
      }

      if (doc.children.isNotEmpty) {
        final childPath = _findPathToDocument(doc.children, targetId, currentPath);
        if (childPath.isNotEmpty) {
          return childPath;
        }
      }
    }
    return [];
  }

  /// 切换展开/折叠状态
  void _toggleExpanded(String docId) {
    setState(() {
      if (_expandedIds.contains(docId)) {
        _expandedIds.remove(docId);
      } else {
        _expandedIds.add(docId);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (widget.documents.isEmpty) {
      return const Center(
        child: Text('暂无文档'),
      );
    }

    return ListView.builder(
      itemCount: widget.documents.length,
      itemBuilder: (context, index) {
        return _buildDocumentItem(widget.documents[index]);
      },
    );
  }

  Widget _buildDocumentItem(Document doc) {
    final isSelected = doc.id == widget.selectedDocId;
    final hasChildren = doc.children.isNotEmpty;
    final isExpanded = _expandedIds.contains(doc.id);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ListTile(
          leading: hasChildren
              ? IconButton(
                  icon: Icon(
                    isExpanded ? Icons.expand_more : Icons.chevron_right,
                    size: 20,
                  ),
                  onPressed: () => _toggleExpanded(doc.id),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                )
              : const SizedBox(width: 20),
          title: Text(doc.name),
          selected: isSelected,
          selectedTileColor: Colors.blue.withAlpha(51),
          onTap: () => widget.onDocumentSelected(doc.id),
          dense: true,
        ),
        if (hasChildren && isExpanded)
          Padding(
            padding: const EdgeInsets.only(left: 24.0),
            child: Column(
              children: doc.children
                  .map((child) => _buildDocumentItem(child))
                  .toList(),
            ),
          ),
      ],
    );
  }
}
